package cn.slipi.common.utils;

import cn.slipi.common.constants.TraceConstants;
import cn.slipi.common.context.ThreadContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import java.util.UUID;

/**
 * 请求调用过程参数
 *
 * @author lee
 * @date 2019-08-15
 * @since 1.0.0
 */
public class TraceUtil {

    public static void traceStart(String traceId) {
        if (StringUtils.isBlank(traceId)) {
            traceId = generatorTraceId();
        }
        MDC.put(TraceConstants.TRACE_ID, traceId);
        ThreadContext.putTraceId(traceId);
    }

    public static void traceEnd() {
        MDC.clear();
        ThreadContext.removeAll();
    }

    public static String getCurrentTraceId() {
        return MDC.get(TraceConstants.TRACE_ID);
    }

    private static String generatorTraceId() {
        return UUID.randomUUID().toString();
    }

}
